﻿using System.Collections;
public class Clock {
    public event Action? TickAction;
    public event Action? AlarmAction;
    public Time curTime => new Time(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
    private Queue<Alarm> AlarmQueue = new Queue<Alarm>();

    public void AddAlarm(Alarm alarm) {
        if (!Time.IsLegal(alarm.AlarmTime))
            throw new Exception("AlarmTime Illegal!");
        AlarmQueue.Enqueue(alarm);
    }
    //note:可能有多个闹钟->用一个queue
    public void TurnOnClock() {
        Console.Clear();
        Console.WriteLine("Colck Already Turn On");
        Tick();
        RunAlarm();
    }

    private void Tick() {
        //开启tick
        Thread tickThre = new Thread(() => {
            while (true) {
                TickAction();
                Thread.Sleep(1000);
            }
        });
        tickThre.Start();
    }
    private void RunAlarm() {
        //关闭闹钟的线程s
        Thread alarmThre = new Thread(() => {
            while (AlarmQueue.Count != 0) {
                var curAlarm = AlarmQueue.First();
                if (curAlarm.AlarmTime.EaqualTo(curTime)) {
                    var tmpMinute = curTime.minute; //用于计算响了多久

                    bool isAlrmClosed = false;
                    Thread th = new Thread(() => CloseAlarm(ref isAlrmClosed));
                    th.Start();
                    Console.Write($"\n\rAlarm {curAlarm.Label} Start, Press S to Turn it off.");
                    Console.Write(new string(' ', Console.BufferWidth - Console.CursorLeft));

                    while (curTime.minute - tmpMinute < curAlarm.DurationMinute) {
                        AlarmAction();
                        if (isAlrmClosed)
                            break;
                    }

                    //如果闹钟一直没关，监听线程不会结束，需要主动关闭
                    if (th.ThreadState != ThreadState.Stopped)
                        th.Abort();
                    Console.Write($"\n\rAlarm {curAlarm.Label} Over...");
                    Console.Write(new string(' ', Console.BufferWidth - Console.CursorLeft));

                    AlarmQueue.Dequeue();
                }
            }
        });
        alarmThre.Start();
    }
    private void CloseAlarm(ref bool isAlrmClosed) {
        char input = 'a';   //随便赋值
        while (input != 'S') {
            input = Console.ReadKey().KeyChar;
            if (input == 'S') {
                isAlrmClosed = true;
                break;

            }
        }
    }
}